package top.ahzy.seobench.interfaces.requestBodyParam;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import top.ahzy.seobench.interfaces.RequestBodyParam;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

public class RequestBodyParamArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestBodyParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        RequestBodyParam annotation = parameter.getParameterAnnotation(RequestBodyParam.class);
        String paramName = annotation.value();
        boolean required = annotation.required();

        // 1. 先尝试从请求参数中获取
        String[] paramValues = webRequest.getParameterValues(paramName);
        if (paramValues != null && paramValues.length > 0) {
            return paramValues[0];
        }

        // 2. 如果请求参数中没有，尝试从请求体中获取
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        if (request != null) {
            try (BufferedReader reader = request.getReader()) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                String requestBody = sb.toString();

                // 这里简单实现，实际应用中你可能需要使用JSON解析库如Jackson
                // 来从请求体中提取特定字段
                if (requestBody.contains("\"" + paramName + "\":")) {
                    int start = requestBody.indexOf("\"" + paramName + "\":") + paramName.length() + 3;
                    int end = requestBody.indexOf(",", start);
                    if (end == -1) end = requestBody.indexOf("}", start);
                    if (end == -1) end = requestBody.length();
                    String value = requestBody.substring(start, end).replace("\"", "").trim();
                    return value;
                }
            }
        }

        // 3. 如果都没找到且required=true，抛出异常
        if (required) {
            throw new IllegalArgumentException("Required parameter '" + paramName + "' is not present");
        }

        return null;
    }
}
